package progress.exa6;

import java.io.*;

public class SerializableStudy {

    public static void main(String[] args) throws IOException {
        serializableStudy();
    }

    /**
     * 序列化克隆
     */
    public static void serializableStudy() throws IOException {
        TV changHong = new TV();
        changHong.setName("长虹电视");
        changHong.setPrice(5678);
        ObjectOutputStream outputStream = null;
        ObjectInputStream inputStream = null;
        try {

            System.out.println("原对象："+changHong.toString());
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            outputStream = new ObjectOutputStream(byteArrayOutputStream);
            outputStream.writeObject(changHong);

            inputStream = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
            TV changHongClone = (TV) inputStream.readObject();
            System.out.println("克隆对象："+changHongClone);

            changHong.name = "修改原对象name";
            System.out.println("原对象:"+ changHong);
            System.out.println("克隆对象:"+ changHongClone);
            changHongClone.name = "修改克隆对象name";
            System.out.println("原对象:"+ changHong);
            System.out.println("克隆对象:"+ changHongClone);

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(outputStream!=null) {
                outputStream.close();
            }
            if(inputStream!=null) {
                inputStream.close();
            }
        }
    }
}




/**
 * 被克隆的对象必须实现标记接口Serializable
 */
class TV implements Serializable{

    String name;
    int price;

    public String toString() {
        return "name:"+name+"price:"+price;
    }

    public void setName(String s){
        name =s;
    }

    public void setPrice(int n){
        price = n;
    }

    public String getName(){
        return name;
    }

    public int getPrice(){
        return price;
    }

}